/*
 * main.c
 *
 *  Created on: 2012-3-8
 *      Author: AndyFu
 */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>

#define BUF_SIZE    1024

int main(int argc, char *argv[])
{
	char buf[BUF_SIZE];
	//char sh_str[BUF_SIZE];
	char *insert_str = "ifneq ($(filter __TGDP_ENGINE__, $(PP_OPT_COMMON)), __TGDP_ENGINE__)\nPP_OPT_COMMON += __TGDP_ENGINE__\nendif\n";
	char *cmp_str = "include $(COMMON_OPTIONS_MAK)\n";
//	char *path_in = "./tng/compil.mak";
	char *path_out0 = "./tng/win32/tmp0";
	char *path_out00 = "./tng/win32/tmp00";
//	char *path_in = "H:/workspace/make/Debug/compil.mak";
//	char *path_out0 = "H:/workspace/make/Debugwin32/tmp0";
//	char *path_out00 = "H:/workspace/make/Debugwin32/tmp00";
	FILE *fp;
	FILE *fp_out;
	int len;
	int cmp_status = 1111;

	if ((access(path_out0, F_OK)) == -1)
	{
		system("cp ./tng/compil.mak ./tng/win32/tmp0");
	}

/*
    if ((fp_out = fopen("H:/workspace/make/Debug/win32/tmp0", "r")) == NULL)
    {
    	size_t bytes_in, bytes_out;
    	fp_out = fopen("H:/workspace/make/Debug/win32/tmp0", "wb");
    	fp = fopen("H:/workspace/make/Debug/compil.mak", "rb");

		while ( (bytes_in = fread(buf, 1, BUF_SIZE, fp)) > 0 )
		{
			bytes_out = fwrite(buf, 1, bytes_in, fp_out);
			if ( bytes_in != bytes_out )
			{

				perror("Fatal write error.\n");
				return 4;
			}
			len += bytes_out;
			printf("copying file .... %d bytes copy\n", len);
		}

		fclose(fp);
		fclose(fp_out);
    }
*/

	if((access(path_out00, F_OK)) == -1)
	{
		fp_out = fopen(path_out00, "wt");
		fp = fopen(path_out0, "r");

		while (fgets(buf, 1024, fp) != NULL)
		{
			len = strlen(buf);

			if (len == 30)
			{
				if(strcmp(buf, cmp_str) == 0)
				{
					strcat(buf, insert_str);
				}
			}

			fputs(buf, fp_out);
		}

		fclose(fp);
		fclose(fp_out);
	}


	cmp_status = system("cmp ./tng/compil.mak ./tng/win32/tmp0");
	printf("%d\n", cmp_status);

	cmp_status = system("cmp ./tng/win32/tmp0 ./tng/win32/tmp00");
	printf("%d", cmp_status);

	execl("make_", "clean", NULL);

	return 0;
}
